//
//  CertificationStatesView.swift
//  Exchange
//
//  Created by 孟祥群 on 2018/4/24.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class CertificationStatesView: UIView, UITableViewDataSource, UITableViewDelegate {
    var dataSource: CertificationStatesViewController!
    lazy var tableView:UITableView = UITableView(frame: CGRect.zero, style: UITableViewStyle.plain)
    lazy var nameArr:NSArray = [kText("初级认证"),kText("高级认证")]
    var selectCell:SecurityCenterCell?
    
    init(dataSource: CertificationStatesViewController!) {
        super.init(frame: CGRect.zero)
        
        self.dataSource = dataSource
        self.themeBackground = ThemeManager.ThemeColorKeys.background
        self.setUpUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI() -> Void {
        dataSource.viewModel?.addObserver(self, forKeyPath: "refreshBool", options: [.new,.old], context: nil)
        
        NotificationCenter.default.addObserver(self, selector: #selector(refresh), name: NSNotification.Name.Exchange.primarycertification, object: nil)
        
        self.addSubview(tableView)
        tableView.separatorStyle = UITableViewCellSeparatorStyle.none
        tableView.backgroundColor = UIColor.clear
        tableView.delegate = self
        tableView.dataSource = self
        tableView.snp.makeConstraints { (make) in
            make.left.right.bottom.top.equalToSuperview()
        }
    
    }
    
    
    /// KVO监听属性
    ///
    /// - Parameters:
    ///   - keyPath: 被监听的属性名
    ///   - object:
    ///   - change:
    ///   - context:
    @objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "refreshBool" {
            tableView.reloadData()
        }
        
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if (dataSource.viewModel?.isChinese)! {
            
            return 3
        }else {
            return 2
        }
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let identy = "identy"
        var cell = tableView.dequeueReusableCell(withIdentifier: identy) as? SecurityCenterCell
        if cell == nil {
            cell = SecurityCenterCell(style: .default, reuseIdentifier: identy)
            if indexPath.row == 0 {
                selectCell = cell
            cell?.contentView.addSubview((cell?.iconImage)!)
            cell?.iconImage.snp.makeConstraints({ (make) in
                make.left.equalTo(15)
                make.centerY.equalToSuperview()
            })
                cell?.nameLabel.snp.updateConstraints({ (make) in
                    make.left.equalToSuperview().offset(48)
                })
          }
            cell?.tag = indexPath.row
            cell?.setArrowImage()
        }
        if indexPath.row == 0 {
            let model = Helper.getCountryModel(with: (dataSource.viewModel?.model.country)!)
            if model != nil {
                if AppCacheInfo.default.isEnlish {
                    cell?.nameLabel.text = model?.countryEnglishName
                }else {
                    cell?.nameLabel.text = model?.countryChineseName
                }
            }else {
                cell?.nameLabel.text = dataSource.viewModel?.model.country
            }
            cell?.statesLabel.text = ""
            if !(dataSource.viewModel?.model.primaryAuth)! && (dataSource.viewModel?.isChinese)! {
                cell?.nameLabel.text = kText("中国")
            }
            if cell?.nameLabel.text?.count != 0 {
                cell?.iconImage.image = UIImage(named: Helper.checkCountryImageName(name: (cell?.nameLabel.text!)!))
            }
        }else if indexPath.row == 1 && (dataSource.viewModel?.isChinese)!{
            cell?.nameLabel.text = kText("初级认证")
            cell?.statesLabel.text = (dataSource.viewModel?.model.primaryAuth)! ? kText("已认证") : kText("未认证")
        }else {
            cell?.nameLabel.text = kText("高级认证")
            if dataSource.viewModel?.model.seniorAuth == 2 {
                cell?.statesLabel.text = kText("未通过")
            }else if dataSource.viewModel?.model.seniorAuth == 1 {
                cell?.statesLabel.text = kText("待审核")
            }else if dataSource.viewModel?.model.seniorAuth == 3{
                cell?.statesLabel.text = kText("已认证")
            }else {
                cell?.statesLabel.text = kText("未认证")
            }
            
        }
            return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 53
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        if indexPath.row == 0 {
            if dataSource.viewModel?.model.seniorAuth != 0  {
                if AppSecurityInfo.default.model.seniorAuth != 2 {
                return
                }
            }
            if (dataSource.viewModel?.model.primaryAuth)! {
                return
            }
            let controller = CountrySelectedViewController()
            controller.delegate = self
            self.dataSource.navigationController?.pushViewController(controller, animated: true)
            
        }else if indexPath.row == 1 && (dataSource.viewModel?.isChinese)!{
            if (dataSource.viewModel?.model.primaryAuth)! {
                CYMBShow.showMessage(kText("初级认证已完成"))
                return
            }
            let controller = CertificationViewController()
            controller.viewModel?.isChinese = true
            self.dataSource.navigationController?.pushViewController(controller, animated: true)
            
        }else {
            if !(dataSource.viewModel?.model.primaryAuth)! && (dataSource.viewModel?.isChinese)!{
                CYMBShow.showMessage(kText("请先完成初级认证"))
                return
            }
            if AppSecurityInfo.default.model.seniorAuth == 0 ||  AppSecurityInfo.default.model.seniorAuth == 2 {
                if !(dataSource.viewModel?.isChinese)! {
                    let controller = CertificationViewController()
                    controller.viewModel?.isChinese = false
                    controller.viewModel?.country = (selectCell?.nameLabel.text)!
                    self.dataSource.navigationController?.pushViewController(controller, animated: true)
                }else {
                    let controller = CertifiPhotoViewController()
                    controller.viewModel?.name = (dataSource.viewModel?.model.userName)!
                    controller.viewModel?.isChinese = (dataSource.viewModel?.isChinese)!
                    controller.viewModel?.country = (dataSource.viewModel?.model.country)!
                    self.dataSource.navigationController?.pushViewController(controller, animated: true)
                }
            }else if AppSecurityInfo.default.model.seniorAuth == 1 || AppSecurityInfo.default.model.seniorAuth == 3{
                let controller = CertifyConditionViewController()
                controller.viewModel?.isSuccess = AppSecurityInfo.default.model.seniorAuth == 1 ? false : true
                self.dataSource.navigationController?.pushViewController(controller, animated: true)
            }else {
                
            }
        }
    }
    
    @objc func refresh() {
        dataSource.viewModel?.archiveInformation()
        NotificationCenter.default.post(name: NSNotification.Name.Exchange.securityDidChange, object: nil)
    }
    
    deinit {
        dataSource.viewModel?.removeObserver(self, forKeyPath: "refreshBool", context: nil)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.Exchange.primarycertification, object: nil)
    }
    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
extension CertificationStatesView: CountrySelectDelegate {
    func selectCountry(model: CountryModel) {
        selectCell?.nameLabel.text = model.countryChineseName
        selectCell?.iconImage.image = UIImage(named: model.countryFlagName)
        dataSource.viewModel?.model.country = model.countryChineseName
        if model.countryChineseName == kText("中国") {
            dataSource.viewModel?.isChinese = true
        }else {
            dataSource.viewModel?.isChinese = false
        }
        if AppCacheInfo.default.isEnlish {
            dataSource.viewModel?.model.country = model.countryEnglishName
        }
        tableView.reloadData()
    }
    
    
    
}
